package org.example;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private static final List<User> USER_LIST = new ArrayList<>();
    static {
        USER_LIST.add(new User(1L, "张三", 20));
        USER_LIST.add(new User(2L, "李四", 22));
    }

    @GetMapping
    public List<User> getAllUsers() {
        return USER_LIST;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return USER_LIST.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .orElse(null); // 若找不到返回 null
    }

    @PostMapping
    public String addUser(@RequestBody User user) {
        USER_LIST.add(user);
        return "新增成功！用户ID：" + user.getId();
    }

    @PutMapping
    public String updateUser(@RequestBody User user) {
        USER_LIST.forEach(u -> {
            if (u.getId().equals(user.getId())) {
                u.setName(user.getName());
                u.setAge(user.getAge());
            }
        });
        return "修改成功！";
    }
}